﻿using System;

namespace SoftwareConsulting.BI11.NumericalMethods.Integration
{    
    /// <summary>
    /// Класс метода Чебышева
    /// </summary>
    public class ChebyshevIntegration
    {
        private double[,] _result;

        /// <summary>
        /// Конструктор по умолчанию
        /// </summary>
        /// <param name="function">Функция, требующая решения</param>
        /// <param name="a">Нижняя граница интеграла</param>
        /// <param name="b">Верхняя граница интеграла</param>
        /// <param name="pointsNumber">Число точек</param>
        public ChebyshevIntegration(FunctionWithOneArgument function, double a, double b, int pointsNumber)
        {            
            double h = 0;
            double j = 0;
            double stepResult = 0;
            int she = 4;            
            _result = new double[2, pointsNumber+1];
            for (int i = 0; i <= pointsNumber; i++)
            {
                h = (b - a) / (double)she;
                she += 4;
                stepResult = 0;
                for (j = a; j <= b; j = j + h)
                {
                    stepResult = stepResult + CalculateChebyshevFunction(j, j + h, function);
                }
                _result[0, i] = stepResult;
                _result[1, i] = h;
            }
        }

        /// <summary>
        /// Выполняет метод Чебышева
        /// </summary>
        /// <param name="A"></param>
        /// <param name="B"></param>
        /// <param name="function"></param>
        /// <returns></returns>
        private double CalculateChebyshevFunction(double A, double B, FunctionWithOneArgument function)
        {
            double[] t = { 0, -0.832498, -0.374513f, 0, 0.374513, 0.832498 };            
            double x = 0;
            double result = 0;
            for (int k = 1; k <= 5; k++)
            {
                x = (double)(A + B) / 2 + (double)(B - A) * (double)t[k] / 2;
                result += function(x);
            }
            result = result * (B - A) / 5;
            return result;
        }

        /// <summary>
        /// Возвращает решение
        /// </summary>        
        public double[,] GetSolution()
        {
            return _result;
        }
    }
}
